package resource

import (
	"mallgo/internal/common/response"
	"mallgo/internal/resources/app/api/domain/request"
	"mallgo/internal/resources/app/model"
	"time"

	"gorm.io/gorm"
)

type AppMenuResource struct {
	db *gorm.DB
}

func NewAppMenuResource(db *gorm.DB) *AppMenuResource {
	return &AppMenuResource{db}
}

// Create 创建应用菜单
func (h *AppMenuResource) Create(req *request.AppMenuRequest) *response.ResponseObject {
	// 检查编码是否已存在
	var existingMenu model.AppMenu
	if err := h.db.Where("code = ?", req.Code).First(&existingMenu).Error; err == nil {
		return response.Error(500, "该菜单编码已存在")
	}

	// 创建菜单
	menu := model.AppMenu{
		Code:       req.Code,
		Name:       req.Name,
		Depth:      req.Depth,
		SortNum:    req.SortNum,
		Catalog:    req.Catalog,
		Icon:       req.Icon,
		MenuType:   req.MenuType,
		Path:       req.Path,
		Permission: req.Permission,
		Router:     req.Router,
		AppID:      req.AppID,
		ParentID:   req.ParentID,
		AddDate:    time.Now(),
		LastDate:   time.Now(),
	}

	if err := h.db.Create(&menu).Error; err != nil {
		return response.Error(500, "创建菜单失败")
	}

	return response.Success(menu)
}

// Update 更新应用菜单
func (h *AppMenuResource) Update(id int64, req *request.AppMenuRequest) *response.ResponseObject {
	var menu model.AppMenu
	if err := h.db.First(&menu, id).Error; err != nil {
		return response.Error(500, "菜单不存在")
	}

	// 检查编码是否与其他记录重复
	if req.Code != menu.Code {
		var existingMenu model.AppMenu
		if err := h.db.Where("code = ? AND id != ?", req.Code, id).First(&existingMenu).Error; err == nil {
			return response.Error(500, "该菜单编码已存在")
		}
	}

	// 更新菜单信息
	updates := map[string]interface{}{
		"code":       req.Code,
		"name":       req.Name,
		"depth":      req.Depth,
		"sort_num":   req.SortNum,
		"catalog":    req.Catalog,
		"icon":       req.Icon,
		"menu_type":  req.MenuType,
		"path":       req.Path,
		"permission": req.Permission,
		"router":     req.Router,
		"app_id":     req.AppID,
		"parent_id":  req.ParentID,
		"last_date":  time.Now(),
	}

	if err := h.db.Model(&menu).Updates(updates).Error; err != nil {
		return response.Error(500, "更新菜单失败")
	}

	return response.Success(menu)
}

// Delete 删除应用菜单
func (h *AppMenuResource) Delete(id int64) *response.ResponseObject {
	// 检查是否存在子菜单
	var count int64
	if err := h.db.Model(&model.AppMenu{}).Where("parent_id = ?", id).Count(&count).Error; err != nil {
		return response.Error(500, "检查子菜单失败")
	}
	if count > 0 {
		return response.Error(500, "存在子菜单，无法删除")
	}

	// 删除菜单
	if err := h.db.Delete(&model.AppMenu{}, id).Error; err != nil {
		return response.Error(500, "删除菜单失败")
	}

	return response.Success(nil)
}

// Get 获取应用菜单详情
func (h *AppMenuResource) Get(id int64) *response.ResponseObject {
	var menu model.AppMenu
	if err := h.db.First(&menu, id).Error; err != nil {
		return response.Error(500, "菜单不存在")
	}

	return response.Success(menu)
}

// Query 查询应用菜单列表
func (h *AppMenuResource) Query(req *request.AppMenuRequest) *response.ResponseObject {
	var menus []model.AppMenu
	var total int64
	query := h.db.Model(&model.AppMenu{})

	// 添加查询条件
	if req.Code != "" {
		query = query.Where("code LIKE ?", "%"+req.Code+"%")
	}
	if req.Name != "" {
		query = query.Where("name LIKE ?", "%"+req.Name+"%")
	}
	if req.AppID != 0 {
		query = query.Where("app_id = ?", req.AppID)
	}
	if req.ParentID != 0 {
		query = query.Where("parent_id = ?", req.ParentID)
	}

	// 获取总数
	if err := query.Count(&total).Error; err != nil {
		return response.Error(500, "查询菜单总数失败")
	}

	// 分页查询
	page := req.Page
	if page <= 0 {
		page = 1
	}
	pageSize := req.PageSize
	if pageSize <= 0 {
		pageSize = 10 // 默认每页10条
	}
	offset := (page - 1) * pageSize

	// 执行分页查询
	if err := query.Offset(offset).Limit(pageSize).Find(&menus).Error; err != nil {
		return response.Error(500, "查询菜单失败")
	}

	// 构造分页响应数据
	result := map[string]interface{}{
		"list":      menus,
		"total":     total,
		"page":      page,
		"page_size": pageSize,
	}

	return response.Success(result)
}
